<?php

namespace App\Console\Commands;

use App\Http\Models\Mysql\SsyMaterialImagesLogTable;
use App\Http\Models\Mysql\SsyMaterialImagesTable;
use App\Http\Repository\CommonRepository;
use App\Http\Repository\SzdptechRepository;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use ZipArchive;

class downloadMaterialImg extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:downloadMaterialImg {--id=} {--auto=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时下载数加物料档案图片';

    /**
     * Create a new command instance.
     * 15,30 2 * * *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        $autoKey = "auto_downloadMaterialImg";
        Cache::put($autoKey, 1, Carbon::now()->addMinutes(15));
        $ids = $this->option("id") ?? "";
        $auto = $this->option("auto") ?? true;
        $cacheFile = storage_path("cache/")."materialImg".".zip";
        if(!empty($ids)){//物料id手动处理
            $ids = explode(",", $ids);
        }elseif($auto){
            //判断日志今日是否已成功抓取
            $log = (new SsyMaterialImagesLogTable())->where('createtime', '>', date("Y-m-d 00:00:00"))->first();
            if(!empty($log) && !empty($log->value)){
                Cache::forget($autoKey);
                die("今日已处理");
            }
            $res = SzdptechRepository::searchMaterialImgs();
            info("物料档案图片", [$res]);
            if(empty($res)){
                Cache::forget($autoKey);
                die("未获取到接口数据");
            }
            //存储抓取日志
            $url = isset($res['value']) && is_string($res['value']) ? $res['value'] : "";
            if(empty($url)){
                Cache::forget($autoKey);
                die(json_encode($res, JSON_UNESCAPED_UNICODE));
            }
            // 第一步：下载远程文件到本地临时目录
            $ch = curl_init($url);
            $fp = fopen($cacheFile, 'wb');
            curl_setopt($ch, CURLOPT_FILE, $fp);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 生产环境需验证 SSL
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 生产环境需验证 SSL
            curl_exec($ch);
            // 检查下载是否成功
            if (curl_errno($ch) || !file_exists($cacheFile)) {
                echo "错误：下载远程文件失败（系统提示：'系统内部异常，请稍后重试'）\n";
            }
            curl_close($ch);
            fclose($fp);
        }
        if(date("Y-m-d", filemtime($cacheFile)) != date('Y-m-d')){
            die("文件下载失败");
        }
        $num = 0;
        // 初始化ZipArchive
        $zip = new ZipArchive();
        // 打开ZIP文件
        if ($zip->open($cacheFile) === TRUE) {
            // 遍历ZIP文件中的所有文件
            for ($i = 0; $i < $zip->numFiles; $i++) {
                // 获取文件名
                $filename = $zip->getNameIndex($i);
                // 读取文件内容
                $content = $zip->getFromIndex($i);
                $filenameArr = explode(".", $filename);
                $materialId = $filenameArr[0];
                if(!empty($ids)){//物料id手动处理
                    if(!in_array($materialId, $ids)){//非需特殊处理物料id 过滤
                        continue;
                    }
                    CommonRepository::delectCDN("http://cdn.13yu.com/material/{$filename}", "material");
                }
                $imgRes = CommonRepository::uploadCDN($filename, 'material', $materialId, $content);
                $exist = (new SsyMaterialImagesTable())->where('material_id', $materialId)->first();
                echo "正在写入, 物料id: ".$materialId."\n";
                $num++;
                if(empty($exist)){
                    $data = [
                        'images' => $imgRes['file'],
                        'material_id' => $materialId,
                        'createtime' => date('Y-m-d H:i:s')
                    ];
                    (new SsyMaterialImagesTable())->createData($data);
                }else{
                    $id = $exist->id;
                    $data = ['images' => $imgRes['file']];
                    (new SsyMaterialImagesTable())->updateData($id, $data);
                }
            }
            // 关闭ZIP文件
            $zip->close();
            echo (empty($num) ? "没有找到对应的物料图片信息" : "已操作{$num}条物料图片信息") . ",操作结束\n";
        } else {
            echo 'Failed to open the zip file.';
        }
        Cache::forget($autoKey);
    }
}
